import { App } from 'vue';
import { createFocusDirective } from './focusDirective';
import Service from './utils/service';
import { RouteLocationNormalized, Router } from 'vue-router';
import keepAliveStore from './utils/store';
import { OptionType } from './types/focus';

export default (app: App, options?: OptionType) => {
  if (!app.config.globalProperties.$Focus) {
    const service: Service = new Service(app, options);
    app.config.globalProperties.$Focus = service;
    app.directive('items', createFocusDirective(service, 'items'));
    app.directive('group', createFocusDirective(service, 'group'));

    const router: Router = app.config.globalProperties.$router;
    if (router) {
      router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized) => {
        service.monitor = false;
        if (from.name !== to.name) {
          // 不同页面跳转时初始化按键响应内容
          service.resetEvent();
        }
        service.createView(to);
        return true
      });
      router.afterEach(() => {
        service.monitor = true;
        options?.includeAttr && keepAliveStore().setPages(options?.includeAttr);
      })
    } else {
      console.warn("路由配置未注册/未使用路由功能！")
    }
  } else {
    console.warn("焦点插件已注册，请勿重复注册！");
  }
};

export { keepAliveStore }
